# -*- coding: utf-8 -*-

from time import time 
import logging
from twisted.internet import task

log = logging.getLogger("AlicanteHomebox")

class Channel:
    def __init__(self):
        self.eventsList = {}
        self.terminals = set([]) #List the terminals watching this channel
        self.videoIP = None
        self.videoPORT = None
        self.fluteIP = None
        self.flutePORT = None
      
    def setParams(self, videoIP, videoPORT, fluteIP, flutePORT):
        self.videoIP = videoIP
        self.videoPORT = videoPORT
        self.fluteIP = fluteIP
        self.flutePORT = flutePORT
      
    def addEvent(self, element):
        if self.eventsList.has_key(element.serviceID):
            if element.version > self.eventsList[element.serviceID].version:
                log.debug("Event with new version received")
                del self.eventsList[element.serviceID]
                self.eventsList[element.serviceID] = element
                # Todo: Deal with the feedback data
            else:
                raise KeyError("Duplicate element")
        else:
            self.eventsList[element.serviceID] = element
            for terminal in self.terminals:
                terminal.updateListEvents()
                terminal.sendAvailableEvents()
    
        
    def addTerminal(self, terminal):
        self.terminals.add(terminal)
          
    def removeTerminal(self, terminal):
        self.terminals.remove(terminal)
        ## Delete channel if no more terminal watching it?
             
        
    def onTimer(self):
        now = time()
        newInteraction = False
        for interaction in self.eventsList.itervalues():
            if not interaction.running() and (interaction.startTime < now < interaction.endTime):
                log.debug("Should show service: %s" % interaction.serviceID)
                interaction.start()
                newInteraction = True
            elif interaction.running() and (interaction.endTime < now):
                log.debug("Should hide service: %s" % interaction.serviceID)
                interaction.stop()
                for terminal in self.terminals:
                    terminal.hideInteraction(interaction.serviceID)
          
        if newInteraction:
            for terminal in self.terminals:
                terminal.updateListEvents()
                terminal.sendAvailableEvents()

class TimeManager:
    def __init__(self, channelsList):
        self.channelsList = channelsList
        self.timer = None
        self.count = 0
        self.fluteManager = None
      
    def runTimer(self):
        self.timer = task.LoopingCall(self.onTimer)
        self.timer.start(4)
      
    def stopTimer(self):
        if self.timer:
            self.timer.cancel()
      
    def onTimer(self):
        log.debug("Timer")
    
        for each in self.channelsList.itervalues():
            each.onTimer()
            if len(each.terminals):
                if self.fluteManager and each.fluteIP and each.flutePORT:
                    self.fluteManager.shouldListen(each.fluteIP, each.flutePORT)
            elif self.fluteManager:
                self.fluteManager.shouldNotListen(each.fluteIP, each.flutePORT)
      
    def addToTMD(self, element):
        if not self.channelsList.has_key(element.channelID):
            self.channelsList[element.channelID] = Channel()
          
        try:
            self.channelsList[element.channelID].addEvent(element)
        except KeyError, e:
            log.error("Error: %s" % e)
        else:
            log.debug("Element added to TMD. Now %d element(s) in %s" % ( len(self.channelsList[element.channelID].eventsList), element.channelID) )
    
    
    def addMappingInfo(self, mappingInfos):
        for channelID, channelInfos in mappingInfos.iteritems():
            if not self.channelsList.has_key(channelID):
                self.channelsList[channelID] = Channel()
    
                self.channelsList[channelID].setParams(
                    channelInfos['AVIP'],
                    channelInfos['AVPORT'],
                    channelInfos['FLUTEIP'],
                    channelInfos['FLUTEPORT'] )
    
    
    def removeFromTMD(self):
        pass


if __name__ == '__main__':
    test = TimeManager()
    test.runTimer()
